package main

import (
	"MailTimer/MailFormat"
	"MailTimer/global"
	"MailTimer/logger"
	"MailTimer/model"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
	"time"
)

var (
	Rdb  *redis.Client
	ZMap = make(map[string]string)
)

func main() {
	//连接redis
	err := GetRedisConn()
	if err == nil {
		ticker := time.NewTicker(3 * time.Minute)//设置定时周期（3分钟去查询一个次缓存）
		go func() {
			for {
				m := make(map[string]string)
				// 获取redis数据
				ZMap = GetRedisZSet(m)
				if len(ZMap) != 0 {
					//获取收件人信息
					gr := MailFormat.GetRecipient()
					//发送邮件
					err2 := MailFormat.SendMail(gr)
					if err2 != nil {
						logger.MyLogger.WithFields(logrus.Fields{"SendMail": "发送邮件失败"}).Info("连接server失败")
						return
					}
				}
				//时间定时器
				myTicker := <-ticker.C
				fmt.Println("时间间隔: ", myTicker)
			}
		}()
	}
	select {}//让主线程阻塞
}

//获取redis连接
func GetRedisConn() error {
	db := redis.NewClient(&redis.Options{
		Addr:     global.Redis126.Host,
		Password: global.Redis126.Pass,
		PoolSize: 200,
		DB:       1,
	})

	srt, err := db.Ping().Result()
	if err != nil {
		logger.MyLogger.WithFields(logrus.Fields{"srt": "是否连接成功"}).Info("连接redis失败")
		return err
	}
	fmt.Println("redis连接: ", srt)
	Rdb = db
	return nil
}

//获取redis数据
func GetRedisZSet(m map[string]string) map[string]string {
	var cursor uint64
	keys, cursor, err := Rdb.Scan(cursor, "*", 1000).Result()
	if err != nil {
		logger.MyLogger.WithFields(logrus.Fields{"key": "redis"}).Info("加载redis所有key失败")
		return nil
	}
	//遍历redis数据库为1的所有key
	for _, key := range keys {
		_, err1 := Rdb.Type(key).Result()
		if err1 != nil {
			logger.MyLogger.WithFields(logrus.Fields{"key": "redis"}).Info("遍历key失败")
			return nil
		}
		//获取Redis 集合
		val, err2 := Rdb.Get(key).Result()
		if err2 != nil {
			logger.MyLogger.WithFields(logrus.Fields{"key": "redis"}).Info("通过遍历key,读取redis value失败")
			return nil
		}
		m[key] = val
	}
	return m
}

func Unmarshal(st *model.Marshal, str string) *model.Marshal {
	b := []byte(str)
	_ = json.Unmarshal(b, &st)
	return st
}
